﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace Kokomo.PeInspector.ObjectGraphs
{
	class PropertyTemplate<TProperty> : MemberTemplate<TProperty>
	{
		public PropertyInfo Property { get; private set; }
		public string PropertyName { get; private set; }

		public PropertyTemplate(
			PropertyInfo property,
			NodeTemplate<TProperty> template
			)
			: base(template)
		{
			if (property == null) throw new ArgumentNullException("property");
			this.Property = property;
		}
		public PropertyTemplate(
			string propertyName,
			NodeTemplate<TProperty> template
			)
			: base(template)
		{
			if (propertyName == null) throw new ArgumentNullException("propertyName");
			this.PropertyName = propertyName;
		}

		private PropertyInfo GetProperty(object target)
		{
			PropertyInfo property = this.Property ?? target.GetType().GetProperty(this.PropertyName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			return property;
		}

		protected override object GetValue(object target)
		{
			PropertyInfo property = this.GetProperty(target);
			return property.GetValue(target, null);
		}

		protected override void SetValue(object target, object value)
		{
			PropertyInfo property = this.GetProperty(target);
			property.SetValue(target, value, null);
		}
	}
}
